package com.huanwang.commonlibrary.networkframework.consumer

import android.util.Log
import com.google.gson.JsonParseException
import io.reactivex.rxjava3.functions.Consumer
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException


abstract class OnResponseListenImpl<T> : Consumer<Any> {
    abstract fun onNoxt(accept: T)
    abstract fun onError(mag: String?)
    abstract fun onComplete()

    override fun accept(t: Any) {
        if (t is Throwable) {
            getMessage(t);
        } else {
            onNoxt(t as T);
        }
        onComplete()
    }

    private fun getMessage(e: Throwable?) {
        var msg: String? = e!!.message
        if (e is UnknownHostException ||
            e is ConnectException
        ) {
            msg = "(╯▽╰)网络开小差了..."
        } else if (e is SocketTimeoutException) {
            msg = "网络连接超时"
        } else if (e is JsonParseException
            || e is JSONException
        ) {
            msg = "解析错误"
        } else if (e is HttpException) {
            val httpException = e
            val code = httpException.code()
            msg = httpException.message()
            if (code == 504) {
                msg = "网络不给力"
            }
            if (code == 500) {
                msg = "请求失败"
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试"
            }
        }
        Log.d("TAGTAG", "OnResponseListenImpl------------$msg")
        onError(msg)
    }

}